package com.sort;

import java.util.*;

/**
 * @author yijy
 * @description
 * @create 2021/4/2 下午4:13
 **/
public class MinHeapSort {

    public static void main(String []args){
        int []arr = {7,6,7,11,5,12,3,0,1,8,9,20,18,16,13};
        for(int i=arr.length/2+1; i>= 0; i--) {
            adjustHeap(arr, i, arr.length);
        }
        System.out.println(Arrays.toString(arr));
        for(int i=arr.length-1; i>=0; i--){
            swap(arr, 0,i);
            adjustHeap(arr,0, i);
        }
        System.out.println("排序后："+Arrays.toString(arr));

    }

    public static void adjustHeap(int[] arr, int i, int length) {
        int temp = arr[i];
        for(int k=2*i+1; k < length; k=2*k+1) {
            if(k+1 < length && arr[k] > arr[k+1]) {
                k++;
            }
            if(arr[k] < temp){
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }

        arr[i] = temp;

    }

    public static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
